package com.zty.controller;

import com.zty.DO.FileChunkMeta;
import com.zty.DO.MetaFile;
import com.zty.DTO.CompleteChunkFileDTO;
import com.zty.DTO.FileMeta;
import com.zty.VO.BucketVO;
import com.zty.response.CommonResponse;
import com.zty.service.MetaService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @Author ZTY
 * @Description 元数据接口
 * @Date 0:53 2023-12-23
 **/

@Validated
@RestController
@RequestMapping("/meta")
public class MetaController {

    private final MetaService metaService;

    public MetaController(MetaService metaService) {
        this.metaService = metaService;
    }

    //  根据上传上来的文件信息去生成对应的元信息
    @PostMapping("/generate")
    public CommonResponse<MetaFile> generate(@Validated @RequestBody FileMeta fileMeta){
        MetaFile metaFile = metaService.generate(fileMeta);
        return CommonResponse.success(metaFile);
    }

    //  获取对应的元信息
    @GetMapping("/info")
    public CommonResponse<MetaFile> info(@RequestParam("bucketName") @NotBlank(message = "存储桶名不得为空") String bucketName,
                                         @RequestParam("filename") @NotBlank(message = "文件名不得为空") String filename){
        MetaFile metaFile = metaService.meta(bucketName,filename);
        return CommonResponse.success(metaFile);
    }

    //  Meta协助Client修改文件分片状态，文件分片状态为true才表示分片已上传成功
    @PostMapping("/chunk/complete")
    public CommonResponse<Void> chunkComplete(@Validated @RequestBody CompleteChunkFileDTO completeChunkFileDTO){
        metaService.completeChunk(completeChunkFileDTO);
        return CommonResponse.success();
    }

    //  上传文件时获取文件的某个分片信息
    @GetMapping("/chunk/info")
    public CommonResponse<List<FileChunkMeta>> chunkInfo(@RequestParam @NotBlank(message = "存储桶名不得为空") String bucketName,
                                       @RequestParam @NotBlank(message = "文件名不得为空") String filename,
                                       @RequestParam @NotNull(message = "分片序号不得为空") Integer chunkNo){

        List<FileChunkMeta> chunks = metaService.chunkInfo(bucketName,filename,chunkNo);
        return CommonResponse.success(chunks);
    }

    @GetMapping("/files")
    public CommonResponse<List<BucketVO>> files(){
        List<BucketVO> files = metaService.files();
        return CommonResponse.success(files);
    }

    @DeleteMapping("{bucketName}/{filename}")
    public CommonResponse<Void> delete(@PathVariable @NotBlank(message = "存储桶名不得为空") String bucketName,
                                       @PathVariable @NotBlank(message = "文件名不得为空") String filename){
        metaService.delete(bucketName,filename);
        return CommonResponse.success();
    }

}
